//
//  PhotoBrowserViewController.swift
//  weibo1
//
//  Created by changhongliang on 2017/8/2.
//  Copyright © 2017年 richinfo. All rights reserved.
//

import UIKit
import SVProgressHUD

class PhotoBrowserViewController: UIViewController {

    ///所有需要显示的图片
    var urls: [NSURL]
    ///当前点击图片的索引
    var path: IndexPath
    
    init(urls:[NSURL],path:IndexPath) {
        self.urls = urls
        self.path = path as IndexPath
        //自定义构造方法需要调用的是designated对应的方法
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //1.添加子控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        //2.布局子控件
        closeButton.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(20)
            make.bottom.equalTo(view).offset(-20)
            make.size.equalTo(CGSize(width: 100, height: 30))
        }
        
        saveButton.snp.makeConstraints { (make) in
            make.right.equalTo(view).offset(-20)
            make.bottom.equalTo(view).offset(-20)
            make.size.equalTo(CGSize(width: 100, height: 30))
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        //注册cell
        collectionView.register(BrowserCollectionViewCell.self, forCellWithReuseIdentifier:  "browserCell")
        
        //设置collectionView滚动到指定的区域
        //注意点是scrollview必须设置contsize调下面的方法才有用
//        let contentOffsetX = ScreenWidth * (CGFloat)(self.path.item )
//        collectionView.setContentOffset(CGPoint(x: contentOffsetX, y: 100), animated: false)
   }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        // 滚动到指定位置
        collectionView.scrollToItem(at: path, at: UICollectionViewScrollPosition.left, animated: false)
    }
    

    
    // MARK: - 内部控制方法
   @objc fileprivate func closeBtnClick()  {
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func saveBtnClick()  {
        //1.获取当前显示的索引
        let path = collectionView.indexPathsForVisibleItems.first!
        //2.获取当前显示的cell
        let cell = collectionView.cellForItem(at: path) as! BrowserCollectionViewCell
        //3.获取当前显示的image
        guard cell.iconImageView.image != nil else {
            // 没有图片
            SVProgressHUD.setDefaultMaskType(.none)
            SVProgressHUD.showError(withStatus: "没有图片")
            return
        }
        
        //4.保存图片
        /*
         第一个参数: 需要保存的图片
         第二个参数: 谁来监听是否保存成功
         第三个参数: 监听是否保存成功的方法名称
         第四个参数: 给监听方法传递的参数
         注意; 监听是否保存成功的方法必须是系统指定的方法*/
        UIImageWriteToSavedPhotosAlbum(cell.iconImageView.image!, self,  #selector(PhotoBrowserViewController.image(image:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?)
    {
        if error != nil
        {
            SVProgressHUD.setDefaultMaskType(.none)
            SVProgressHUD.showError(withStatus: "保存图片失败")
            return
        }
        SVProgressHUD.setDefaultMaskType(.none)
        SVProgressHUD.setMinimumDismissTimeInterval(1.0)
        SVProgressHUD.showSuccess(withStatus:"保存图片成功")
    }
    
    // MARK: - 懒加载
    lazy var closeButton:UIButton = {
        let btn = UIButton()
        btn.setTitle("关闭", for: .normal)
        btn.backgroundColor = UIColor(white: 0.8, alpha: 0.5)
        btn.addTarget(self, action: #selector(PhotoBrowserViewController.closeBtnClick), for: .touchUpInside)
        return btn
    }()
    
    lazy var saveButton:UIButton = {
        let btn = UIButton()
        btn.setTitle("保存", for: .normal)
        btn.backgroundColor = UIColor(white: 0.8, alpha: 0.5)
        btn.addTarget(self, action: #selector(PhotoBrowserViewController.saveBtnClick), for: .touchUpInside)
        return btn
    }()
    
    lazy var layout:HLPhotoBrowserLayout = HLPhotoBrowserLayout()
    
    lazy var collectionView:UICollectionView = {
        let clv:UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.layout)
        clv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "browserCell")
        clv.dataSource = self
        clv.backgroundColor = UIColor.green
        let contentSizeWidth = ScreenWidth * (CGFloat)(self.urls.count)
        clv.contentSize = CGSize(width: contentSizeWidth , height: ScreenHeight)
        return clv
    }()

    
    
    
}

extension PhotoBrowserViewController: UICollectionViewDataSource,BrowserCollectionViewCellDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "browserCell", for: indexPath) as! BrowserCollectionViewCell
        cell.url = urls[indexPath.row] as URL
        cell.backgroundColor = UIColor.orange
        cell.delegate = self 
        return cell
    }
    
    func broserCollectionViewCellDidClick(cell:BrowserCollectionViewCell) {
          closeBtnClick()
    }

}



class HLPhotoBrowserLayout: UICollectionViewFlowLayout {
    override func prepare() {
        itemSize = UIScreen.main.bounds.size
        scrollDirection = UICollectionViewScrollDirection.horizontal
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        collectionView?.bounces = false
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.isPagingEnabled = true
    }
}
